﻿using Forum.Model.Entity.System;
using Forum.Model.Pager;
using Forum.Model.QueryFilters;
using Forum.Repository.Extensions;
using Forum.Repository.Interface;
using Forum.Service.Interface.System;

namespace Forum.Service.Service.System
{
    public class SysMenuService : ISysMenuService
    {
        private readonly IAppRepository<SYS_MENU> _menuRepo;
        public SysMenuService(IAppRepository<SYS_MENU> menuRepo)
        {
            _menuRepo = menuRepo;
        }

        /// <summary>
        /// 分页查询菜单
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public IPagedList<SYS_MENU> GetPagedList(QueryParameters param)
        {
            var querySet = _menuRepo.SugarQueryable;

            // 关键词过滤
            if (!string.IsNullOrEmpty(param.Search))
            {
                querySet = querySet.Where(a => a.NAME.Contains(param.Search) || a.PATH.Contains(param.Search));
            }
            // 排序
            querySet = querySet.OrderBy(a => a.SORT);
            if (!string.IsNullOrEmpty(param.SortBy))
            {
                // 是否升序
                var ascending = !param.SortBy.StartsWith("-") ? " asc" : " desc";
                var orderByProperty = param.SortBy.Trim('-');

                querySet = querySet.OrderBy(orderByProperty + ascending);
            }
            var menuList = querySet.ToPage(param.Page, param.PageSize);

            return menuList;
        }

        /// <summary>
        /// 查询用户菜单
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        public List<SYS_MENU> GetMenuList(string? userId)
        {
            var menuList = this._menuRepo.Db.Queryable<SYS_MENU>()
                 .InnerJoin<SYS_ROLE_MENU>((a, b) => a.ID == b.MENU_ID)
                 .InnerJoin<SYS_USER_ROLE>((a, b, c) => b.ROLE_ID == c.ROLE_ID)
                 .WhereIF(!string.IsNullOrWhiteSpace(userId), (a, b, c) => c.USER_ID == userId)
                 .Where((a, b, c) => a.ISACTIVE == "Y" && b.ISACTIVE == "Y" && c.ISACTIVE == "Y")
                 .ToList();

            var parentMenuList = menuList.Where(a => a.PARENTID == null).ToList();
            foreach (var menu in parentMenuList)
            {
                menu.Children = menuList.Where(a => a.PARENTID != null && a.PARENTID.Value == menu.ID).ToList();
            }

            return parentMenuList ?? new List<SYS_MENU>();
        }
    }
}
